package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmsorder.entity.OrderCostDept;
import com.sunda.spmsorder.mapper.OrderCostDeptMapper;
import com.sunda.spmsorder.service.IOrderCostDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 订单费用承担部门 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-04-20
 */
@Service
public class OrderCostDeptServiceImpl extends ServiceImpl<OrderCostDeptMapper, OrderCostDept> implements IOrderCostDeptService {

    @Override
    public int updateOderCostDept(JSONArray array) {
        if (StringUtils.isEmpty(array.toString()) || array.size() == 0){
            return 0;
        }
        int result = 0;
        for (int i = 0; i < array.size(); i++){
            JSONObject doc = array.getJSONObject(i);
            OrderCostDept orderCostDept = new OrderCostDept();
            orderCostDept.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
            orderCostDept.setDeptId(Integer.parseInt(doc.getString("id")));
            orderCostDept.setDeptName(doc.getString("name"));
            orderCostDept.setSuperiorDept(Integer.parseInt(doc.getString("supid")));
            QueryWrapper<OrderCostDept> queryWrapper = new QueryWrapper<OrderCostDept>().eq("DEPT_ID", orderCostDept.getDeptId());
            OrderCostDept costDept = this.baseMapper.selectOne(queryWrapper);
            if (costDept != null){
                result += this.baseMapper.update(orderCostDept, queryWrapper);
            }else {
                result += this.baseMapper.insert(orderCostDept);
            }
        }
        return result;
    }

    @Override
    public List<OrderCostDept> getOrderCostDept() {
        /** 前端取数只取 父级部门id 大于等于0 的数据即可 */
        // return this.baseMapper.selectList(new QueryWrapper<OrderCostDept>().ge("SUPERIOR_DEPT", 0));
        return this.baseMapper.selectList(new QueryWrapper<OrderCostDept>());
    }

    @Override
    public List<Map<String, Object>> getOrderCostDeptLevel() {
        return this.baseMapper.getOrderCostDeptLevel();
    }
}
